﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ClientApp.UtilClasses
{
    /// <author> 
    ///     Luke Chircop 
    ///     Adrian De Barro 
    /// </author
    /// <summary>
    ///     Offers functionality related to processes
    /// </summary>
    class ProcessHelperFunctions
    {
        
        public static void StartProcess()
        {
            //get Bat File name from app.config
            string fileName = ConfigurationManager.AppSettings["BatFile"].ToString();
            string currentDirectory = Directory.GetCurrentDirectory();
            System.Diagnostics.Process batchProc = new System.Diagnostics.Process
            {
                //Setting up 
                StartInfo =
                {
                    FileName = fileName,
                    WorkingDirectory = currentDirectory
                }
            };

            batchProc.Start();
            Console.WriteLine("Batch process started");
        }


        public static bool CloseProcess(string pProcessName)
        {
             Process runningProcess = null;

            //For all currently running processes 
            foreach (Process p in Process.GetProcesses())
            {
                try
                {
                    //Check if the module name corresponds to the executable that you want to monitor
                    if (!p.MainModule.ModuleName.Contains(pProcessName)) continue;
                    //Printing to confirm...
                    //Save process to use for checking...
                    runningProcess = p;
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
            }

            //If process was found....
            if (runningProcess != null)
            {
                try
                {
                    runningProcess.Kill();
                    return true;
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.StackTrace);
                    return false;
                }
                
            }

            return true;
        }

        public static void MonitorProcess()
        {
            string processName = ConfigurationManager.AppSettings["ProcessName"].ToString();
            CheckProcessRunning(processName);
            Communication.Communication.SendJobTerminated();
        }


        public static void CheckProcessRunning(string pProcessName)
        {
            Thread.Sleep(2000);
            //Starting process checking 
            int timeInterval = 1000;//One second
            Process runningProcess = null;

            //For all currently running processes 
            foreach (Process p in Process.GetProcesses())
            {
                try
                {
                    //Check if the module name corresponds to the executable that you want to monitor
                    if (!p.MainModule.ModuleName.Contains(pProcessName)) continue;
                    //Printing to confirm...
                    //Save process to use for checking...
                    runningProcess = p;
                }
                catch
                {
                    // ignored
                }
            }

            //If process was found....
            if (runningProcess != null)
            {
                try
                {   // Repeat until the process stops executing
                    while (!runningProcess.HasExited)
                    {
                        //Timing to prevent flooding of cpu usage.. 
                        Thread.Sleep(timeInterval);
                        // Refreshing process information
                        runningProcess.Refresh();
                    }
                }
                catch(Exception e)
                {
                    //Error
                    Console.WriteLine(e.StackTrace);
                }
            }
            else
            {
                Console.WriteLine("Process never detected");
            }

            Console.WriteLine();
        }

    }
}
